import { useStore } from '@/hooks';
import { Form, Select, ResponsiveGrid, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';

const { Cell } = ResponsiveGrid;

const CompanySelect = (props) => {
  const {
    calculate,
    handleChange,
    handleChangeTableDataSource,
    name,
    value,
    record,
    type,
    mode,
  } = props;
  const { orderChangeStore: store } = useStore();
  const { dataSource = [] } = toJS(store.options.company).find((e) => e.type === type) || {};
  const curCompanyIds = dataSource.reduce((res, cur) => {
    const { value: companyId } = cur;
    res.push(companyId);
    return res;
  }, []);

  const [curSurcharges, setCurSurcharges] = useState({});
  const [curValue, setCurValue] = useState(value);

  useEffect(() => {
    (async () => {
      const { ORDER: order } = record;
      if (value) {
        if (curCompanyIds.includes(value)) {
          const data = dataSource.find((e) => e.value === value)?.surcharge || {};
          setCurSurcharges(data);
          handleChangeTableDataSource(data);
          setCurValue(value);
        } else {
          setCurValue(record?.companyName);
          handleChangeTableDataSource(record?.surcharges);
        }
      }
    })();
  }, [value]);


  useEffect(() => {
    (async () => {
      if (value) {
        try {
          const curSurchargeKeys = Object.keys(curSurcharges);
          const { selectedSurchargeKeys = [] } = record;
          if (!selectedSurchargeKeys?.every((key) => curSurchargeKeys.includes(key))) {
            throw (t`当前公司附加费不包含已选附加费`);
          }
        } catch (error) {
          Dialog.warning({
            content: t`${error}`,
          });
        }
      }
    })();
  }, [curSurcharges]);

  function handleCompanyPicked(companyId, _, optionData) {
    const pathMap = {
      direct: 'order.ccOrder.companyId',
      from: 'order.ccOrder.transferLinePrice.fromRoute.companyId',
      to: 'order.ccOrder.transferLinePrice.toRoute.companyId',
    };
    calculate.setParam(pathMap[type], optionData?.value);
    calculate.setParam('newCompanyId', optionData?.value);
    calculate.setParam('newCompanyName', optionData?.label);
    handleChange?.(record, {
      name: 'company',
      value: {
        surcharges: optionData?.surcharge,
        driver: undefined,
        licenseNo: {
          hk: undefined,
          mainland: undefined,
        },
        companyName: optionData?.label,
        companyId: optionData?.value,
      },
    });
  }

  return (
    <>
      <ResponsiveGrid gap={[0, 24]} columns={4}>
        <Cell colSpan={1} className={`grid-${2}`}>
          <Form.Item
            label={t`所属公司`}
            name={name}
            mode={mode}
            style={{ width: '100%' }}
          >
            <Select
              value={curValue}
              dataSource={dataSource}
              hasClear
              onChange={handleCompanyPicked}
            />
          </Form.Item>
        </Cell>
      </ResponsiveGrid>
    </>
  );
};

export default observer(CompanySelect);
